<template>
  <el-dialog v-model="model" title="修改地址" width="40%">
    <el-form :model="addressForm" :rules="addressRules" ref="addressFormEditRef" label-width="80px">
      <el-form-item label="收货人" prop="consignee">
        <el-input v-model="addressForm.consignee" placeholder="请输入收货人"></el-input>
      </el-form-item>
    <!-- 省份 -->
      <el-form-item label="省份" prop="province">
        <el-select v-model="addressForm.province" placeholder="请选择省份" @change="onProvinceChange" style="width: 100%">
          <el-option
            v-for="item in provinces"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 城市 -->
      <el-form-item label="城市" prop="city">
        <el-select v-model="addressForm.city" placeholder="请选择城市" @change="onCityChange" style="width: 100%">
          <el-option
            v-for="item in cities"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 区县 -->
      <el-form-item label="区县" prop="district">
        <el-select v-model="addressForm.district" placeholder="请选择区县" style="width: 100%">
          <el-option
            v-for="item in districts"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" prop="detail">
        <el-input v-model="addressForm.detail" placeholder="请输入详细地址"></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="addressForm.phone" placeholder="请输入手机号码"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="model = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">修 改</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineExpose, defineProps, watch,onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import regions from '@/assets/data/pca.json'; // 引入地区数据

axios.defaults.baseURL = "http://localhost:8080";

const model = defineModel(); // 支持 v-model 控制显示隐藏

// 地址表单
const addressForm = ref({
  consignee: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  phone: ''
});

// 接收父组件传来的当前地址 ID 和地址数据
const props = defineProps({
  currentEditIndex: {
    type: [String, Number],
    required: true
  },
  currentAddress: {
    type: Object,
    default: null
  }
});

// 初始化表单
const initAddressForm = (address) => {
  addressForm.value = {
    consignee: address.consignee || '',
    province: address.province || '',
    city: address.city || '',
    district: address.district || '',
    detail: address.detail || '',
    phone: address.phone || ''
  };

  if (address.province) {
    onProvinceChange(address.province); // 加载城市列表

    if (address.city) {
      // 异步延迟确保城市列表已加载
      setTimeout(() => {
        addressForm.value.city = address.city;
        onCityChange(address.city); // 加载区县列表

        if (address.district) {
          setTimeout(() => {
            addressForm.value.district = address.district;
          }, 50);
        }
      }, 50);
    }
  }
};

// 省市区数据
const provinces = ref([]);
const cities = ref([]);
const districts = ref([]);

// 初始化省份列表
onMounted(() => {
  for (const key in regions) {
    if (regions.hasOwnProperty(key)) {
      provinces.value.push({ label: key, value: key });
    }
  }
});

const onProvinceChange = (selectedProvince) => {
  const selectedProvinceData = regions[selectedProvince];
  if (selectedProvinceData) {
    cities.value = Object.keys(selectedProvinceData).map(cityKey => ({
      label: cityKey,
      value: cityKey
    }));
    addressForm.value.city = '';
    addressForm.value.district = '';
  } else {
    cities.value = [];
    districts.value = [];
  }
};

const onCityChange = (selectedCity) => {
  const selectedCityData = regions[addressForm.value.province]?.[selectedCity];
  if (selectedCityData) {
    districts.value = selectedCityData.map(district => ({
      label: district,
      value: district
    }));
    addressForm.value.district = '';
  } else {
    districts.value = [];
  }
};
// 监听 model 变化，初始化表单数据
watch(
  () => model.value,
  (newValue) => {
    if (newValue && props.currentAddress) {
      initAddressForm(props.currentAddress);
    }
  },
  { immediate: true }
);

// 提交逻辑
const emit = defineEmits(['confirm']);

const handleConfirm = async () => {
  try {
    const token = sessionStorage.getItem('token');
    const addressId = parseInt(props.currentEditIndex, 10);
    const response = await axios.put(`/address/modify/${addressId}`, addressForm.value, {
      headers: {
        Authorization: `${token}`
      }
    });

    if (response.data.code === 0) {
      ElMessage.success('地址修改成功');
      emit('confirm', addressForm.value);
      model.value = false;
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    console.error('修改地址失败:', error);
    ElMessage.error('修改地址失败');
  }
};

defineExpose({ addressForm });
</script>